package com.epoch.platform.sys.user.service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.epoch.base.util.MD5Utils;
import com.epoch.platform.sys.org.dao.SysOrg;
import com.epoch.platform.sys.user.dao.SysUser;
import com.epoch.platform.sys.userorg.dao.SysUserOrg;
import com.epoch.platform.sys.userrole.dao.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

public class SysUserService {
	
	public static final String USER_AUTOGRAPH_BUSI_TYPE = "Autograph";
	
	@Before(Tx.class)
    public void saveSysUser(SysUser model, Map<String, List<SysUserRole>> userSysRolesMap) throws IOException {
        String deptId = model.getStr(SysUser.DEPT_ID);
        String companyId = "0";
        SysOrg sysOrg = SysOrg.dao.findById(deptId);
        if (sysOrg != null) {
            companyId = sysOrg.get(SysOrg.PARENT_ID, "0");
        }
        model.set(SysUser.COMPANY_ID, companyId);
        model.set(SysUser.PASSWORD, MD5Utils.getMd5("123456"));
        model.saveOrUpdate();
        // 获取用户ID
        String userId = model.getStr(SysUser.ID);
        if (userId != null) {
            // 删除原有组织
            Db.update(Db.getSql("systemManage.deleteUserOrgByUserId"),  userId);
            // 重新保存用户组织数据
            SysUserOrg userOrg = new SysUserOrg();
            userOrg.set(SysUserOrg.USER_ID, userId);
            userOrg.set(SysUserOrg.ORG_ID, deptId);
            userOrg.save();
            // 删除原有角色
            Db.update(Db.getSql("systemManage.deleteUserRoleByUserId"),  userId);
            // 重新保存用户角色数据
            this.saveUserRoles(userSysRolesMap.get("newRows"), userId);
            this.saveUserRoles(userSysRolesMap.get("editRows"), userId);
        }
    }
    
    @Before(Tx.class)
    public void deleteUserByIds(String[] userIdStrs) {
        if (userIdStrs != null) {
            int cnt = userIdStrs.length;
            int i = 0;
            for (; i < cnt; i++) {
                String userId = new String(userIdStrs[i]);
                //删除组织
                Db.update(Db.getSql("systemManage.deleteUserOrgByUserId"), userId);
                //删除角色
                Db.update(Db.getSql("systemManage.deleteUserRoleByUserId"), userId);
                SysUser.dao.deleteById(userId);
            }
        }
    }
    
    private void saveUserRoles(List<SysUserRole> roles, String userId) {
        for (SysUserRole role : roles) {
            role.set(SysUserRole.ID, null);
            role.set(SysUserRole.USER_ID, userId);
            role.save();
        }
    }

}
